String a= "" 与 String a = new String()区别 您所在的位置:网站首页 for string a:b String a= "" 与 String a = new String()区别

String a= "" 与 String a = new String()区别

2024-07-12 04:00| 来源: 网络整理| 查看: 265

String a = “a”;

String b = “a”;

String c = “c”;

区别:

1、’直接定义的String “a”'c’是储存在 常量存储区中的字符串常量池中;new String(“a”)是存储在堆中;

2、常量池中相同的字符串只会有一个,但是new String(),每new一个对象就会在堆中新建一个对象,不管这个值是否相同;

String a = “a” String b = “a” a b都指向字符串常量池中的“a”,所以 a==b 为 true;

String a = new String(“a”) String b = new String(“a”);是会在堆中创建两个对象new String() “a”是常量池中的”a”,这两个对象的值都为 a,所以a==b 返回false;a.equals(b)返回true;

3、

String a = “a”在编译阶段就会在内存中创建;

String a = new String(“a”);是在运行时才会在堆中创建对象

参考:

http://www.cnblogs.com/luckyliu/archive/2012/04/05/2433657.html

http://blog.sina.com.cn/s/blog_5edcfe6a0100d7u2.html

区别具体体现在于值相等内存地址是否相同 ==判断地址 .equals判断值(String重写了equals,equals本身也是判断地址) 同时往map里放值 例如往HashMap放值 值相等时只能放一个 不能放下两个 参考: https://www.cnblogs.com/aspirant/p/9193112.html

a instanceof b a是否是b的实例 是返回true 例如

“sss“ instanceof String //true; String s = null; s instanceof String //false System.out.println(new Image() instanceof String); //compile time error System.out.println(new Image() instanceof Exception); //compile time error System.out.println(new Image() instanceof Object); //compilation and output true System.out.println(new Image() instanceof List); //compilation and output false System.out.println(new Image() instanceof List); //compilation and output false System.out.println(new Image() instanceof List); //compile time error System.out.println(new Image() instanceof List); //compile time error System.out.println(new Image() instanceof List); //compile time error System.out.println(new String() instanceof List); //compile time error System.out.println(null instanceof Object); //compilation and output false


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有